import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

import Home from '@/views/home'
import Login from '@/views/login'
import Layout from '@/views/layout'

import Project from '@/views/backend/project'
import Doc from '@/views/backend/doc'
import Workbench from '@/views/backend/workbench'

let router = new Router({
  mode: 'history',
  linkActiveClass: 'is-active',
  routes: [

    //首页
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    //后台
    {
      path: '/management',
      name: 'Management',
      component: Layout,

      children: [
        {
          path: '/project',
          name: 'Project',
          component: Project,
          meta: {
            login: true
          }
        },

        {
          path: '/workbench',
          name: 'Workbench',
          component: Workbench,
          meta: {
            login: true
          }
        },

        {
          path: '/doc',
          name: 'Doc',
          component: Doc,
          meta: {
            login: false
          }
        },
      ]
    },
    //登录
    {
      path:'/login',
      name:Login,
      component:Login
    },

    {
      //没有组件对应的路由，重定向到根目录
      path:'*',
      redirect:'/'
    }
  ]
})

router.beforeEach(function (to,from,next){
  console.log(to)
  /*
   * matched: to下面的一个属性，该属性是一个数组，数组中保存了当前目标路由对象和它的父路由信息
   *
   * 数组中的some方法：判断子路由和父路由是否需要登录，只要有一个需要登录，我们就要跳转到登录页面
   * */
  let boolean=to.matched.some(function (item){

    return item.meta.login;

  })

  if(boolean){
    //router.app=>vm对象
    let info=router.app.$local.fetch('miaov');

    if(info.login){
      next();
    }else{
      router.push({
        path:'/login',
        //通过query部分，实现当我们登录的时候，跳转到指定的页面，如workbench
        query:{
          redirect:to.path.slice(1)
        }
      })
    }
  }else{
    next();
  }
})

export default router;
